package com.yupi.oj.judge;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.oj.judge.codesandbox.CodeSandbox;
import com.yupi.oj.judge.codesandbox.CodeSandboxFactory;
import com.yupi.oj.judge.codesandbox.CodeSandboxProxy;
import com.yupi.oj.judge.codesandbox.model.ExecuteCodeRequest;
import com.yupi.oj.judge.codesandbox.model.ExecuteCodeResponse;
import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.exception.BusinessException;
import com.yupi.oj.judge.strategy.DefaultJudgeStrategy;
import com.yupi.oj.judge.strategy.JudgeContext;
import com.yupi.oj.judge.strategy.JudgeStrategy;
import com.yupi.oj.mapper.QuestionSubmitMapper;
import com.yupi.oj.model.dto.question.JudgeCase;
import com.yupi.oj.judge.codesandbox.model.JudgeInfo;
import com.yupi.oj.model.entity.Question;
import com.yupi.oj.model.entity.QuestionSubmit;
import com.yupi.oj.model.enums.QuestionSubmitStatusEnum;
import com.yupi.oj.service.QuestionService;
import com.yupi.oj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class JudgeServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements JudgeService {
    @Value("${codesandbox.type}")
    public String type;
    @Resource
    private QuestionSubmitService questionSubmitService;
    @Resource
    private QuestionService questionService;
    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit==null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"提交题目异常：提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question==null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"提交题目异常：提交题目不存在");
        }
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"提交题目异常：提交的题目判题中");
        }
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());

        boolean save = questionSubmitService.updateById(questionSubmitUpdate);
        if (!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新异常");
        }
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type); //工厂模式选择指定type的沙箱
        CodeSandboxProxy sandboxProxy = new CodeSandboxProxy(codeSandbox);//使用代理方便增强，类似AOP
        String submitLanguage = questionSubmit.getLanguage();
        String submitCode = questionSubmit.getCode();

        //获取输入用例
        String judgeCaseStr= question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        //交给代码沙箱执行
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(submitCode)
                .language(submitLanguage)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = sandboxProxy.executeCode(executeCodeRequest);
        //得到运行的结果
        List<String> outputList = executeCodeResponse.getOutputList();

        //获取judgeContext上下文
        JudgeStrategy judgeStrategy = new DefaultJudgeStrategy();
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        judgeStrategy.doJudge(judgeContext);

        //执行判题策略
        JudgeManager judgeManager = new JudgeManager();
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        //更新提交结果
        QuestionSubmit newQuestionSubmit = new QuestionSubmit();
        newQuestionSubmit.setId(questionSubmitId);
        newQuestionSubmit.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        newQuestionSubmit.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        boolean update = questionSubmitService.updateById(newQuestionSubmit);
        if (!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新异常");
        }
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionId);
        return questionSubmitResult;
    }
}
